const express = require('express')
const Router = express.Router()
const query = require('./db')

module.exports = Router

/**
 * 获取所有用户信息
 */
Router.get('/getUserList', async (req, res) => {
    try {
        let data = await query(`select * from user`)
        if (data.length == 0) {
            res.send({
                status: 400,
                msg: '获取用户列表失败'
            })
            return
        }
        res.send({
            status: 200,
            msg: '获取用户列表成功',
            data
        })
    } catch (error) {
        res.send({
            status: 0,
            error
        })
    }
})

/**
 * 冻结/解冻操作
 */
Router.post('/changeIce', async (req, res) => {
    try {
        let { user_id, user_status } = req.body
        let sql = ''
        if (user_status == '正常') {
            sql = `update user set user_type='2' where user_id=${user_id}`
        } else {
            sql = `update user set user_type='1' where user_id=${user_id}`
        }
        let data = await query(sql)
        res.send({
            status: 200,
            msg: '修改用户状态成功',
            data
        })
    } catch (error) {
        res.send({
            status: 0,
            error
        })
    }
})

/**
 * 查询用户数量
 */
Router.get('/getUserCount', async (req, res) => {
    try {
        let data = await query(`select * from user`)
        if (data.length === 0) {
            res.send({
                status: 400,
                msg: '没有用户',
            })
            return
        }
        let ice = data.filter(item => item.user_type == '2').length
        let normal = data.filter(item => item.user_type == '1').length
        res.send({
            status: 200,
            msg: '查询用户数量成功',
            count: {
                length: data.length,
                ice,
                normal
            }
        })
    } catch (error) {
        res.send({
            status: 0,
            error
        })
    }
})

/**
 * 获取所有待审核的文章信息
 */
Router.get('/getArticleList', async (req, res) => {
    try {
        let data = await query(`select * from article join type on article.article_type=type.type_id where article_status='0'`)
        if (data.length == 0) {
            res.send({
                status: 400,
                msg: '没有待审核的文章',
                data
            })
            return
        }
        res.send({
            status: 200,
            msg: '获取待审核文章成功',
            data
        })
    } catch (error) {
        res.send({
            status: 0,
            error
        })
    }
})

/**
 * 改变选中的文章的状态
 */
Router.post('/changeArticleStatus', async (req, res) => {
    try {
        let { article_ids, status } = req.body
        let sql = `update article set article_status='${status}' where `
        article_ids.forEach(item => {
            item *= 1
            sql += `article_id=${item} or `
        })
        sql = sql.slice(0, -3)
        let data = await query(sql)
        res.send({
            status: 200,
            msg: '修改文章状态成功（通过）'
        })

    } catch (error) {
        res.send({
            status: 0,
            error
        })
    }
})

/**
 * 获取各文章类型的占比
 */
Router.get('/getTypePercent', async (req, res) => {
    try {
        let articleData = await query(`select * from article `)
        let typeData = await query(`select * from type`)
        let typeResult = typeData.map(item => {
            return {
                value: 0,
                name: item.type_name
            }
        })
        articleData.forEach(item => {
            typeResult[item.article_type - 1].value++
        })
        res.send({
            code: 200,
            typeResult
        })
    } catch (error) {
        res.send({
            status: 0,
            error
        })
    }
})

/**
 * 获取最受欢迎作者
 */
Router.get('/getHotAuthor', async (req, res) => {
    try {
        let userData = await query(`select * from user`)
        let articleData = await query(`select * from article join likes on article.article_id=likes.article_id`)
        // 遍历所有用户
        let userResult = userData.map(item => {
            let likeCount = 0
            // 在每个用户中遍历所有文章，找到当前用户的文章就加上点赞数
            articleData.forEach(i => {
                if (i.article_author_id === item.user_id) {
                    likeCount += (parseInt(i.article_like) + parseInt(i.article_collect))
                }
            })
            return {
                user_id: item.user_id,
                user_name: item.user_name,
                user_avatar: item.user_avatar,
                likeCount
            }
        })
        let data = userResult.sort((a, b) => (b.likeCount - a.likeCount)).slice(0, 5)
        res.send({
            code: 200,
            data
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})


/**
 * 获取最受欢迎文章
 */
Router.get('/getHotArticle', async (req, res) => {
    try {
        let data = await query(`select * from article`)
        if (data.length == 0) {
            res.send({
                status: 400,
                msg: '没有文章',
            })
            return
        }
        res.send({
            status: 200,
            msg: '获取文章成功',
            data
        })
    } catch (error) {
        res.send({
            status: 0,
            error
        })
    }
})

/**
 * 获取每月发布的文章数量
 */
Router.get('/getMonthArticleCount', async (req, res) => {
    try {
        let articleData = await query(`select * from article`)
        let result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        // articleData.forEach((item, index) => {

        //     let month = new Date(Number(item.article_time)).getMonth()
        //     result.forEach((i, idx) => {
        //         if (idx == month) {
        //             i++
        //         }
        //     })
        // })
        // result.forEach((item, index) => {
        //     let count = 0
        //     articleData.forEach((i, idx) => {
        //         let month = new Date(Number(i.article_time)).getMonth()
        //         if (index == month) {
        //             count++
        //         }
        //     })
        //     item = count
        //     console.log(item);
        // })
        for (let i = 0; i < result.length; i++) {
            articleData.forEach((item, index) => {
                let month = new Date(Number(item.article_time)).getMonth()
                if (i == month) {
                    result[i]++
                }
            })
        }
        res.send({
            code: 200,
            msg: '获取每月文章数量成功',
            result
        })
    } catch (error) {
        res.send({
            status: 0,
            error
        })
    }
})
